package com.wu.client.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.wu.client.cache.newData.NewAlbumCache;
import com.wu.client.cache.newData.NewSongCache;
import com.wu.client.constant.ResTypeEnum;

import com.wu.client.dto.AlbumMongo;
import com.wu.client.dto.SongMongo;
import com.wu.mongo.NewData;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Cousin
 * @date 2025/3/20
 * @Description
 */
@Component
@RequiredArgsConstructor
public class NewSchedule {
    private final MongoTemplate mongoTemplate;
    @PostConstruct
    public void onStartup() {
        // 启动时立即调用任务
        refreshNewAlbumCacheData();
        refreshNewSongCacheData();
    }

    // 每天凌晨 4 点 1分钟执行
    @Scheduled(cron = "0 1 4 * * ?")
    public void refreshNewSongCacheData(){
        Integer code = ResTypeEnum.SONG.getCode();
        Query query = new Query();
        query.addCriteria(Criteria.where("resType").is(code));
        // 排序：按 createTime 字段降序
        query.with(Sort.by(Sort.Order.desc("createTime")));
        NewData<SongMongo> newData = mongoTemplate.findOne(query, NewData.class);
        if(ObjectUtil.isNotNull(newData)){
            List<SongMongo> info = newData.getInfo();
            NewSongCache.getInstance().setSongMongoList(info);
        }
    }
    @Scheduled(cron = "0 2 4 * * ?")
    public void refreshNewAlbumCacheData(){
        Integer code= ResTypeEnum.ALBUM.getCode();
        Query query = new Query();
        query.addCriteria(Criteria.where("resType").is(code));
        // 排序：按 createTime 字段降序
        query.with(Sort.by(Sort.Order.desc("createTime")));
        NewData<AlbumMongo> newData = mongoTemplate.findOne(query, NewData.class);
        if(ObjectUtil.isNotNull(newData)){
            List<AlbumMongo> info = newData.getInfo();
            NewAlbumCache.getInstance().setAlbumMongoList(info);
        }
    }
}
